package com.itheima.service.Impl;

import com.itheima.common.constant.MessageConstant;
import com.itheima.exception.orderException;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.*;
import com.itheima.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
    private final OrderMapper orderMapper;
    private final RedisTemplate redisTemplate;


    @Override
    public OrderVO findById(Integer id) {
        return orderMapper.findById(id);
    }

    @Override
    public void submitOrder(OrderDTO order) {
        // 验证验证码
        String code = order.getValidateCode();
        Object validateCode = redisTemplate.opsForValue().get("telephone");
        if (validateCode != null && !code.equals(validateCode.toString())) {
            throw new orderException(MessageConstant.VALIDATECODE_ERROR);
        }
        // 验证预约日期是否设置预约人数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(order.getOrderDate());
        OrderSetting orderSettingByMonth = orderMapper.getOrderSettingByMonth(dateStr);
        if (orderSettingByMonth==null){
            throw new orderException(MessageConstant.GET_ORDERSETTING_FAIL);
        }
        // 验证预约人数是否已满
        int reservations = orderSettingByMonth.getReservations();
        if (reservations>=orderSettingByMonth.getNumber()){
            throw new orderException(MessageConstant.ORDER_FULL);
        }
        // 验证是否已预约
        if (order.getMemberId()!=null){
            Order exitorder = orderMapper.findByMemberId(order);
            if (exitorder!=null){
                throw new orderException(MessageConstant.HAS_ORDERED);
            }
        }
        // 添加会员信息
           Member member = new Member();
           BeanUtils.copyProperties(order,member);
           member.setRegTime(new Date());
           member.setPhoneNumber(order.getTelephone());
        orderMapper.createMember(member);
        order.setMemberId(member.getId());
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);

        // 添加预约信息
        orderMapper.submitOrder(order);
        orderSettingByMonth.setReservations(reservations+1);
        orderMapper.editNumberByOrderDate(orderSettingByMonth);
    }
}
